#include <iostream>
#include <memory>
#include "include/TcpSocket.hpp"
#include "Common.hpp"
#include "Reactor.hpp"
#include "ConnectionFactory.hpp"
#include "Accepter.hpp"

void usage(std::string proc_name)
{
    std::cout << "usage: \n\t" << proc_name << " port\n" << std::endl;
}

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        usage(argv[0]);
        return 1;
    }
    uint16_t port = std::stoi(argv[1]);

    // 1.创建listen套接字，设为非阻塞
    std::unique_ptr<Socket> listen_sock = std::make_unique<TcpSocket>();
    listen_sock->createListenSocket(port);
    setNonBlock(listen_sock->getSocketFd());

    // 2.创建Reactor
    std::unique_ptr<Reactor> svr = std::make_unique<Reactor>();

    // 3.绑定回调方法
    std::unique_ptr<Accepter> accepter = std::make_unique<Accepter>();
    auto listenReader = std::bind(&Accepter::accept, accepter.get(), std::placeholders::_1);

    // 4.创建listen_sock对应的Connection，添加到Reactor中
    svr->addConnection(ConnectionFactory::createListenConnection(listen_sock->getSocketFd(), listenReader, EPOLLIN|EPOLLET, svr.get()));

    // 5.开始事件派发
    svr->start();
    
    return 0;
}